Page({
  data: {
    message: null,
    isOpening: false,
    isOpened: false,
    isPageTurning: false,
    showTimeFlow: false,
    pastTime: ''
  },

  // 处理401错误
  handleUnauthorized() {
    getApp().handleUnauthorized();
  },

  onLoad(options) {
    const { id } = options;
    if (id) {
      this.fetchMessageDetail(id);
    }
  },

  // 获取留言详情
  fetchMessageDetail(id) {
    const token = wx.getStorageSync('token');
    if (!token) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    wx.showLoading({ title: '加载中...' });
    wx.request({
      url: `https://www.haoyuming.online/api/user/message/${id}`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${token}`
      },
      success: (res) => {
        if (res.statusCode === 401) {
          this.handleUnauthorized();
          return;
        }

        if (res.statusCode === 200 && res.data.code === 200) {
          const message = res.data.data;
          // 处理日期格式
          message.createTime = this.formatDate(message.createTime);
          // 获取用户信息
          const userInfo = wx.getStorageSync('userInfo');
          message.avatar = userInfo?.avatarUrl || '/assets/images/default-avatar.png';
          message.nickname = userInfo?.nickName || '匿名用户';
          
          this.setData({ message });
        } else {
          wx.showToast({
            title: res.data?.msg || '获取信息失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
      },
      complete: () => {
        wx.hideLoading();
      }
    });
  },

  // 格式化日期
  formatDate(dateString) {
    if (!dateString) return '';
    const date = new Date(dateString);
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
  },

  // 返回上一页
  onBackTap() {
    wx.navigateBack();
  },

  // 打开信封
  openEnvelope() {
    if (this.data.isOpened || this.data.isOpening) return;
    
    this.setData({ isOpening: true });
    
    // 播放打开信封的音效
    const audio = wx.createInnerAudioContext();
    audio.src = '/assets/sounds/envelope-open.mp3';
    audio.play();
    
    // 添加振动反馈
    wx.vibrateShort({
      type: 'medium'
    });
    
    // 延迟设置完全打开状态
    setTimeout(() => {
      this.setData({ 
        isOpening: false,
        isOpened: true
      });
      
      // 开始翻页动画
      setTimeout(() => {
        this.startPageTurningAnimation();
      }, 500);
    }, 800);
  },

  // 开始翻页动画
  startPageTurningAnimation() {
    const now = new Date();
    const messageDate = new Date(this.data.message.createTime);
    const timeDiff = this.calculateTimeDiff(messageDate, now);
    
    this.setData({
      isPageTurning: true,
      pastTime: timeDiff
    });

    setTimeout(() => {
      this.setData({
        showTimeFlow: true
      });
    }, 300);

    // 翻页动画结束
    setTimeout(() => {
      this.setData({
        isPageTurning: false
      });
    }, 1200);
  },

  // 计算时间差
  calculateTimeDiff(startDate, endDate) {
    const diff = endDate - startDate;
    const days = Math.floor(diff / (1000 * 60 * 60 * 24));
    const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));

    if (days > 0) {
      return `${days}天前`;
    } else if (hours > 0) {
      return `${hours}小时前`;
    } else if (minutes > 0) {
      return `${minutes}分钟前`;
    } else {
      return '刚刚';
    }
  }
}); 